import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import adminApi from '@/services/adminApi';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/login';
const Theme: any = localStorage.getItem('ThemeSwitch');
let ds = defaultSettings;
if (Theme) {
  try {
    // ds = Object.assign(defaultSettings, JSON.parse(Theme));
    ds.navTheme = Theme;
  } catch (e) {
    //console.log(e);
    ds = defaultSettings;
  }
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<
    LayoutSettings & {
      pwa?: boolean;
      logo?: string;
    }
  >;
  currentUser?: API.userItem | undefined;
  loading?: boolean;
  fetchUserInfo?: () => Promise<any | undefined>;
  menuData?: any;
  fetchMenuData?: () => any;
  collapsed?: boolean;
  ver?: (rid: number) => boolean;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await adminApi.cwSys.AdminapiCwSysCurrentuser({}); //AdminapicsSysCurrentuser
      return msg.errorCode === '0' ? msg.data : undefined;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  const fetchMenuData = async () => {
    const menu = await adminApi.cwDev.AdminapiCwDevGetmenu({}); //AdminapiCwMenuGetmenu
    return menu.data;
  };
  const _collapsed = localStorage.getItem('collapsed');
  const collapsed = _collapsed ? _collapsed === 'true' : false;
  // 如果不是登录页面，执行
  if (history.location.pathname !== '/admin/login') {
    const currentUser: any = await fetchUserInfo();
    const menuData: any = await fetchMenuData();
    const verification = (rid: number) => {
      return currentUser.admin ? currentUser.admin : currentUser?.roleIds.includes(rid);
    };
    return {
      fetchUserInfo,
      currentUser,
      fetchMenuData,
      menuData,
      settings: ds,
      collapsed,
      ver: verification,
    };
  }
  return {
    fetchUserInfo,
    fetchMenuData,
    settings: ds,
    collapsed,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    pure: window.location.pathname.includes('/admin/login'),
    token: {
      // header: {
      //   headerBgColor: '#292f33',
      //   headerTitleColor: '#fff',
      //   menuTextColor: '#dfdfdf',
      //   menuTextColorSecondary: '#dfdfdf',
      //   menuSelectedTextColor: '#fff',
      //   menuItemSelectedBgColor: '#22272b',
      //   rightActionsItemTextColor: '#dfdfdf',
      // },
      // appListIconHoverTextColor: '#fff',
      // appListIconTextColor: '#dfdfdf',
      sider: {
        menuBackgroundColor: '#fff',
        menuItemDividerColor: '#dfdfdf',
        menuItemHoverBgColor: '#f6f6f6',
        menuTextColor: '#595959',
        menuSelectedTextColor: '#242424',
        menuItemCollapsedHoverBgColor: '#242424',
      },
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // console.log(initialState?.loading);
      // 如果没有登录，重定向到 api
      if (!initialState?.currentUser && location.pathname !== '/admin/login') {
        history.push(loginPath);
      }
    },
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: initialState,
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      request: async (params, defaultMenuData) => {
        return await initialState?.menuData;
      },
    },
    links: isDev
      ? [
          //umi/plugin/openapi
          <a key="openapi" href={`${API_URL}/swagger-ui.html`} target="_blank" rel="noreferrer">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </a>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // noFound:<div>unAccessible</div>,
    // defaultCollapsed: true,
    siderWidth: 160,
    // collapsed: initialState?.collapsed,
    // onCollapse: (col) => {
    //   console.log(col);
    //   setInitialState((preInitialState) => ({
    //     ...preInitialState,
    //     collapsed: col,
    //   }));
    //   localStorage.setItem('collapsed', `${col}`);
    // },
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      // console.log(history.location.pathname);
      // console.log(window.location.pathname);
      return (
        <>
          {children}
          {!window.location.pathname.includes('/admin/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              hideHintAlert
              hideCopyButton
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                settings.title = initialState?.settings?.title;
                // console.log(JSON.stringify(settings));
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
                // localStorage.setItem('ThemeSwitch', JSON.stringify(settings));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
// src/app.tsx
// const authHeaderInterceptor: any = (url: string, options: RequestConfig) => {
//   const token = localStorage.getItem('token');
//   const authHeader = { token };
//   return {
//     url: `${url}`,
//     options: { ...options, interceptors: true, headers: authHeader },
//   };
// };
// const responseInterceptors: any = (response: Response & Record<string, any>) => {
//   if (response?.data?.status === 403) {
//     history.push({
//       pathname: '/403',
//       search: `?url=${response?.data?.path}`,
//     });
//   }
//   return response;
// };
// export const request: RequestConfig = {
//   // 新增自动添加AccessToken的请求前拦截器
//   requestInterceptors: [authHeaderInterceptor],
//   responseInterceptors: [responseInterceptors],
// };
/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
